Categories
JavaScript Tips

Useful JavaScript Tips — Semicolons, Dates, and Logging Objects

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Semicolon

Semicolons can be automatically inserted in JavaScript.

It inserts semicolons on the next line after code that breaks the current one.

Also, when the next line starts with a } , a semicolon is inserted.

When the end of the source code file is reached, then the semicolon is added.

Semicolons are also inserted after the break keyword.

It’s also added after the throw and continue keywords.

If we don’t add it ourselves, then the interpreter will insert it for us.

Manipulating Dates Easily with Moment.js

To make date manipulating easier, we can use moment.js

We can install it by adding a script tag or installing the package.

We can write:

<script src="https://unpkg.com/moment" />

or:

npm install moment

If we use the package, we can write:

import moment from 'moment'

To get the current date and time, we can write:

const date = moment();

To parse a date, we can write:

const date = moment(string);

It takes various formatting codes. They are:

  • YYYY — 4 digits year
  • YY — 2 digits year
  • M — 2 digits month number without the 0
  • MM — 2 digits month number
  • MMM — 3 letters month name
  • MMMM — full month name
  • dddd — full day name
  • gggg — 4 digits week year
  • gg — 2 digits week year
  • w — week of the year without leading zero
  • ww — week of the year with leading zero
  • e — day of week that starts with 0
  • D — 2 digits day number without the leading 0
  • DD — 2 digits day number
  • Do — day number with ordinal
  • T — start of the time part
  • HH — 2 digit hours from 0 to 23
  • H — 2 digit hours from 0 to 23 without the leading 0
  • kk — 2 digit hours from 1 to 24
  • k — 2 digit hours from 1 to 24 without leading 0
  • a/A — am or pm
  • hh — 2 digit hours (12 hours time)
  • mm — 2 digit minutes
  • ss — 2 digits seconds
  • s — 2 digits seconds without leading 0
  • S — 1 digit milliseconds
  • SS — 2 digit milliseconds
  • SSS — 3 digits milliseconds
  • Z — timezone
  • x — UNIX timestamp in milliseconds

For instance, we can format date by writing:

moment().format("YYYY-MM-DD")

Moment.js comes with a few constants.

They are the following:

  • moment.HTML5_FMT.DATETIME_LOCAL — ‘YYYY-MM-DDTHH:mm’
  • moment.HTML5_FMT.DATETIME_LOCAL_SECONDS — ‘YYYY-MM-DDTHH:mm:ss’
  • moment.HTML5_FMT.DATETIME_LOCAL_MS — ‘YYYY-MM-DDTHH:mm:ss.SSS’
  • moment.HTML5_FMT.DATE — ‘YYYY-MM-DD’
  • moment.HTML5_FMT.TIME — ‘HH:mm’
  • moment.HTML5_FMT.TIME_SECONDS — ‘HH:mm:ss’
  • moment.HTML5_FMT.TIME_MS — ‘HH:mm:ss.SSS’
  • moment.HTML5_FMT.WEEK — ‘YYYY-[W]WW’
  • moment.HTML5_FMT.MONTH — ‘YYYY-MM’

We can validate a date with the isValid method.

For instance, we can write:

moment('2020-13-32').isValid()

which returns false , or:

moment('2020-01-23').isValid()

which returns true .

Get the Relative Time String

We can use the fromNow method to get the relative from the current date and time.

For instance, we can write:

moment("2020-11-23").fromNow()

and get ‘in 6 months’ .

We can pass true to fromNow , then it shows the difference without reference to the future or past.

So if we write:

moment("2020-11-23").fromNow(true)

Then we get ‘6 months’ .

Manipulating Dates

We can use the Moment.js add and subtract methods to add or subtract amounts from a date.

For instance, we can write:

moment('2020-11-23').add(1, 'days');  
moment('2020-11-23').subtract(1, 'days');

The 2nd argument can have the following values:

  • years
  • quarters
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds
  • milliseconds

Inspect a JavaScript Object

There are various ways to inspect objects in JavaScript.

We can use the console.log method to log an expression and get its return value.

For instance, we can write:

console.log(dog)

There’s also the console.dir method to let us inspect any object.

For instance, we can write:

console.dir(dog)

JSON.stringify is another way to let us inspect an object.

It’ll return a string.

For instance, given that we have:

const dog = {  
  color: 'white',  
  breed: 'poodle'  
}

we can write:

console.log(JSON.stringify(dog))

which creates an unprettified string.

Then we get:

{"color":"white","breed":"poodle"}

logged.

To pretty-print the string, we can pass in 2 more arguments.

We write:

console.log(JSON.stringify(dog, null, 2))

and we get:

{  
  "color": "white",  
  "breed": "poodle"  
}

Conclusion

Moment.js makes date manipulating easier than with the Date constructor.

We can inspect expression values with console and JSON.stringify.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *